package com.blb.ssh.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import com.blb.ssh.dao.BaseDao;

@Repository("baseDao")
public class BaseDaoImpl<T> implements BaseDao<T>{
	
	@Resource
	private SessionFactory sessionFactory;
	
	private Class<T> clazz;
	
	//获取真实实现类
	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		Type type = this.getClass().getGenericSuperclass();
		if (type instanceof ParameterizedType) {
			ParameterizedType pType = (ParameterizedType)type;
			clazz = (Class<T>) pType.getActualTypeArguments()[0];
			System.out.println("Dao的真实实现类是：" + this.clazz.getName());
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> getList(int pageNo, int pageSize) {
		Session session = sessionFactory.getCurrentSession();
		Query<T> query = session.createQuery("from " + clazz.getSimpleName());
		query.setFirstResult((pageNo-1)*pageSize);
		query.setMaxResults(pageSize);
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public int getCount(int pageNo, int pageSize) {
		Session session = sessionFactory.getCurrentSession();
		Query<Long> query = session.createQuery("select count(id) from " + clazz.getSimpleName());
		List<Long> list = query.list();
		return list.get(0).intValue();
	}

	@Override
	public void save(T t) {
		sessionFactory.getCurrentSession().save(t);
	}

	@Override
	public void update(T t) {
		sessionFactory.getCurrentSession().update(t);
	}

	@Override
	public void delete(T t) {
		sessionFactory.getCurrentSession().delete(t);
	}

	@Override
	public T findById(Serializable id) {
		return sessionFactory.getCurrentSession().get(this.clazz, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findByHQL(String hql, Object... params) {
		Query<T> query = sessionFactory.getCurrentSession().createQuery(hql);
		for (int i=0; params != null && i < params.length; i++) {
			query.setParameter(i, params[i]);
		}
		return query.list();
	}

}
